﻿using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols;
using Rj_GsInsurance.Server.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Rj_GsInsurance.Server.Utils
{
    public class GSInsuraceHelper
    {
        //[DllImport("HBSiInterface.dll", EntryPoint = "Si_INIT")]
        //public static extern int Si_INIT(StringBuilder pErrMsg);


        //[DllImport("HBSiInterface.dll", EntryPoint = "Si_Busi")]
        //public static extern int Si_Busi(StringBuilder inputdata, StringBuilder outputdata);

        private delegate int Si_INIT(StringBuilder pErrMsg);
        private delegate int Si_Busi(StringBuilder inputdata, StringBuilder outputdata);
        private static Si_INIT si_init = KernelExtensions.CreateDelInstance<Si_INIT>("HBSiInterface.dll", "Si_INIT");
        private static Si_Busi si_busi = KernelExtensions.CreateDelInstance<Si_Busi>("HBSiInterface.dll", "Si_Busi");

        /// <summary>
        /// DLL实现方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="indata"></param>
        /// <param name="outdata"></param>
        /// <returns></returns>
        //[HandleProcessCorruptedStateExceptions]
        public static bool Si_INIT_Handle(out string pErrMsg)
        {
            var outputdata = new StringBuilder(2048);
            try
            {
                var result = si_init(outputdata);
                pErrMsg = outputdata.ToString();
                return result==0;
            }
            catch (Exception ex)
            {
                pErrMsg = ex.ToString();
                return false;
            }
        }

        public static bool Si_Busi_Handle(string inputdata, out string outdata)
        {
            if(!Si_INIT_Handle(out string errMsg))
            {
                outdata=errMsg;
                return false;
            }
            var outputdata = new StringBuilder(204800);
            try
            {
                LogHelper.Info($"医保交易传入:{inputdata}");
                StringBuilder inputStr = new StringBuilder(inputdata);
                var result = si_busi(inputStr, outputdata);
                LogHelper.Info($"医保交易结果:{result}");
                outdata = outputdata.ToString();
                LogHelper.Info($"医保交易返回:{outdata}");
                return result==0;
            }
            catch (Exception ex)
            {
                outdata = ex.ToString();
                return false;
            }
        }
    }
}
